import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../component/custom_app_bar.dart';
import '../util.dart';
import 'model.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

import 'video_player/view.dart';

void gallery(List<GalleryModel> items, {int showIndex = 0}) {
  Get.to(
    () => GalleryPage(
      items: items,
      showIndex: showIndex,
    ),
    transition: Transition.noTransition,
  );
}

class GalleryPage extends StatefulWidget {
  final List<GalleryModel> items;
  final int showIndex;
  late PageController pageCtrl;

  GalleryPage({
    Key? key,
    required this.items,
    required this.showIndex,
  }) : super(key: key) {
    pageCtrl = PageController(initialPage: showIndex);
  }

  @override
  _GalleryPageState createState() {
    return _GalleryPageState();
  }
}

class _GalleryPageState extends State<GalleryPage> {
  late RxInt currentIndex = (widget.showIndex + 1).obs;

  final List<Widget> widgets = [];

  @override
  void initState() {
    super.initState();
    setWidget();
  }

  List<Widget> setWidget() {
    widget.items.forEach((element) {
      if (element.url.contains('jpeg') ||
          element.url.contains('jpg') ||
          element.url.contains('png')) {
        widgets.add(PhotosView(element));
      } else {
        widgets.add(VideoPlayerPage(
          url: element.url,
        ));
      }
    });
    return widgets;
  }

  // 图片
  Widget PhotosView(GalleryModel item) {
    return PhotoView(
      imageProvider: loadImageProvider(url: item.url),
    );
  }

  void onPageChanged(int index) {
    currentIndex.value = (index + 1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: HomeAppBar(context, title: "文件预览"),
      body: Stack(
        children: [
          PageView(
            controller: PageController(initialPage: widget.showIndex),
            children: widgets,
            onPageChanged: onPageChanged,
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              padding: const EdgeInsets.all(20.0),
              child: Obx(() {
                return Text(
                  "$currentIndex / ${widget.items.length}",
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 17.0,
                    decoration: null,
                  ),
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
